package org.sam.beatles.integrations;

import java.util.Collection;

import org.sam.swing.table.JSTableModelEvent;
import org.sam.swing.table.defaultImpl.JSTableModelDefaultAdapter;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * jpa操作数据库的实现
 * 
 * @author sam
 *
 * @param <E>
 */
public class JSTableModelJPAAdapter<E> extends JSTableModelDefaultAdapter<E> {
	
	/**
	 * 当前的数据库操作对象
	 */
	private JpaRepository<E, Integer> dao;

	/**
	 * jpa操作数据库的实现
	 * @param dao
	 */
	public JSTableModelJPAAdapter(JpaRepository<E, Integer> dao) {
		this.dao = dao;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Collection<E> onRetrieve() throws Exception {
		return dao.findAll();
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	@Override
	public boolean update(JSTableModelEvent event) throws Exception {
		try {
			Collection<E> deletes = (Collection<E>) event.getTableModel().getDeletes();
			if (deletes != null && !deletes.isEmpty()) {
				this.dao.deleteAll(deletes);
			}

			Collection<E> creates = (Collection<E>) event.getTableModel().getCreates();
			if (creates != null && !creates.isEmpty()) {
				this.dao.saveAll(creates);
			}

			Collection<E> modifieds = (Collection<E>) event.getTableModel().getModified();
			if (modifieds != null && !modifieds.isEmpty()) {
				this.dao.saveAll(modifieds);
			}

			return true;
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return false;
	}
}
